
package com.work.util;

import java.sql.Time;

import javax.validation.*;

import org.junit.Test;

public class TimeValidator implements ConstraintValidator<CorrectTimeFormat, Time> {

	TimeFormatType format;
	
	@Override
	public void initialize(CorrectTimeFormat timeFormat)
	{
		format = timeFormat.pattern();
	}

	@Override
	public boolean isValid(Time value, ConstraintValidatorContext context)
	{
		System.out.print("TimeValidator.isValid(): " + value);
		if (value == null) {
			System.out.println("Zwracam TRUE");
			return true;
		}
		
		try {
			String textValue = value.toString();
			System.out.print("WARTOSC TEKSTOWA: " + textValue);
			boolean isMatch = textValue.matches(format.getTimePpattern());
			System.out.println("Zwracam " + isMatch);
			return isMatch;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Zwracam FALSE");
			return false;
		}
		
		//System.out.println("Zwracam TRUE");
		//return true;
	}
	
	public enum TimeFormatType {
		HH("([01]?[0-9]|2[0-3])"),
		HH_MM("([01]?[0-9]|2[0-3]):[0-5][0-9]"),
		HH_MM_SS("([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]");
		
		private String timePpattern;
		
		private TimeFormatType(String timePpattern) {
			this.timePpattern = timePpattern;
		}

		public String getTimePpattern()
		{
			return timePpattern;
		}
	};
	
	@Test
	public void test() {
		String time1 = "08:30:00";
		
		Time t1 = Time.valueOf("00:00:00");
		Time t2 = Time.valueOf("01:00:00");
		Time t3 = Time.valueOf("02:00:00");
		Time t4 = Time.valueOf("03:00:00");
		
		System.out.println(time1.matches(TimeFormatType.HH_MM_SS.getTimePpattern()));
		
		
	}
}
